<template>
  <a-drawer
    v-model:visible="vdata.isShow" 
    :title="vdata.isAdd ? '创建蚂蚁店铺' : '修改蚂蚁店铺'"
    width="60%"
    :mask-closable="false"
    @close="vdata.isShow = false"
  >
    <a-form v-if="!vdata.isAdd" :model="vdata.saveObject" :label-col="{span: 6}" :wrapper-col="{span: 15}">
      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <a-form-item label="蚂蚁店铺ID:">
            <a-span>{{ vdata.saveObject.alipayShopId }}</a-span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="蚂蚁店铺状态">
            <a-tag v-if="vdata.saveObject.alipayShopStatus=='0'">未创建</a-tag>
            <a-tag v-else-if="vdata.saveObject.alipayShopStatus=='99'" color="green">审核通过</a-tag>
            <a-tag v-else-if="vdata.saveObject.alipayShopStatus=='-1'" color="red">审核拒绝</a-tag>
            <div v-else>
              <a-tag color="orange">审核中</a-tag>
              <a-button 
                v-if="$access('ENT_MCH_ALIPAY_SHOP_STATUS')" 
                type="primary"
                :size="'small'"
                :loading="vdata.updateLoading"
                @click="updateShopStatusFunc(vdata.saveObject.storeId)"
              >
                <sync-outlined /> 更新状态
              </a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-divider v-if="!vdata.isAdd" />

    <a-form ref="infoFormModel" :model="vdata.saveObject" :label-col="{span: 6}" :wrapper-col="{span: 15}" :rules="rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="12">
          <a-form-item label="门店名称:" name="storeName">
            <a-input v-model:value="vdata.saveObject.storeName" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人电话" name="contactPhone">
            <a-input v-model:value="vdata.saveObject.contactPhone" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="门店类目" name="shopCategory">
            <JeepayAliMccSelect v-model:value="vdata.saveObject.shopCategory" />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.isAdd" :span="12">
          <a-form-item label="店铺经营类型" name="shopType">
            <a-radio-group v-model:value="vdata.saveObject.shopType">
              <a-radio value="01">直营</a-radio>
              <a-radio value="02">加盟</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 引入地图组件  -->
      <JeepayAmap v-if="vdata.isShow" ref="jeepayAmapRef" />
    </a-form>
    
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="vdata.isShow = false"><close-outlined /> 取消</a-button>
      <a-button :style="{ marginRight: '8px' }" type="primary" :loading="vdata.confirmLoading" @click="okFunc"><check-outlined /> 确定</a-button>
      <a-button v-if="$access('ENT_MCH_ALIPAY_SHOP_DELETE') && vdata.saveObject.alipayShopStatus != '0'" type="danger" @click="alipayShopCloseFunc"><close-outlined /> 关闭蚂蚁店铺</a-button>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { req, reqLoad, API_URL_MCH_STORE_LIST, API_ALIPAY_SHOP }from '@/api/manage'
import { reactive, ref, getCurrentInstance, nextTick } from 'vue'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const jeepayAmapRef = ref()
const infoFormModel = ref()

const props = defineProps({
    callbackFunc: {type: Function, default: () => {} }
})

const vdata: any = reactive({
  isAdd: false, // 是否新增
  confirmLoading: false, // 显示确定按钮loading图标
  isShow: false, // 是否显示弹层/抽屉
  saveObject: {} as any, // 数据对象
  recordId: null, // 更新对象ID
})

const rules = {
  areaCode: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
  storeName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系人电话', trigger: 'blur' }],
  shopCategory: [{ required: true, message: '请输入门店类目', trigger: 'blur' }],
  shopType: [{ required: true, message: '请输入店铺经营类型', trigger: 'blur' }]
}


function show (recordId, isAdd) { // 弹层打开事件
  vdata.isAdd = isAdd

  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }

  // 数据恢复为默认数据
  vdata.saveObject = { lng: '', lat: ''}

  vdata.confirmLoading = false // 关闭loading
  vdata.updateLoading = false // 关闭loading
  vdata.isShow = true

  let initMapData : any = {}

  if (!isAdd) {
    vdata.recordId = recordId
    req.getById(API_ALIPAY_SHOP, recordId).then(res => {
      vdata.saveObject = res
      console.log(vdata.saveObject)

      // 门店包含了区域编码
      if(res.areaCode && res.areaCode.length){
        initMapData.areacode = res.areaCode
        initMapData.lnglat = res.lng + ',' + res.lat
        initMapData.address = res.address
      }
      // 显示地图信息
      nextTick(() => jeepayAmapRef.value.init(initMapData))
    })
  }else {
    // 创建蚂蚁店铺，拉取商户门店信息
    vdata.recordId = recordId
    req.getById(API_URL_MCH_STORE_LIST, recordId).then(res => {
      vdata.saveObject = res

      // 门店包含了区域编码
      if(res.areaCode && res.areaCode.length){
        initMapData.areacode = res.areaCode
        initMapData.lnglat = res.lng + ',' + res.lat
        initMapData.address = res.address
      }
      // 显示地图信息
      nextTick(() => jeepayAmapRef.value.init(initMapData))
    })
  }

}

// 创建/修改蚂蚁店铺
function okFunc () {
  let mapData = jeepayAmapRef.value.getMapData()
  if(!mapData || mapData.areacode.length == 0 || !mapData.address || !mapData.lnglat){
    return $infoBox.message.error('请选择地理位置')
  }

  if(mapData.lnglat.indexOf(',') < 0){
    return $infoBox.message.error('请输入正确的经纬度')
  }

  infoFormModel.value.validate().then(valid =>{
    vdata.saveObject.lng = mapData.lnglat.split(',')[0]
    vdata.saveObject.lat = mapData.lnglat.split(',')[1]
    vdata.saveObject.address = mapData.address
    vdata.saveObject.areaCode = JSON.stringify(mapData.areacode)

    vdata.confirmLoading = true // 显示loading

    if (vdata.isAdd) {
      reqLoad.add(API_ALIPAY_SHOP + '/' + vdata.recordId, vdata.saveObject).then(res => {
        vdata.isShow = false
        vdata.confirmLoading = false
        props.callbackFunc() // 刷新列表 
      }).catch(valid =>{
        vdata.confirmLoading = false      
      })
    }else {
      reqLoad.updateById(API_ALIPAY_SHOP, vdata.recordId, vdata.saveObject).then(res => {
        vdata.isShow = false
        vdata.confirmLoading = false
        props.callbackFunc() // 刷新列表 
      }).catch(valid =>{
        vdata.confirmLoading = false      
      })
    }
    
  })
}

function alipayShopCloseFunc () { // 关闭蚂蚁店铺
  $infoBox.confirmDanger('关闭蚂蚁店铺', '确定关闭蚂蚁店铺吗？', () => {
    return reqLoad.delById(API_ALIPAY_SHOP, vdata.recordId).then(res => {
      $infoBox.message.success('关闭成功')
      props.callbackFunc() // 刷新列表
    }).catch(err => console.log(err))
  })
}

function updateShopStatusFunc (recordId) { // 【更新蚂蚁店铺状态】
  vdata.updateLoading = true
  reqLoad.getById(API_ALIPAY_SHOP + '/createResult', recordId, undefined).then(res => {
    vdata.updateLoading = false
    vdata.saveObject.alipayShopStatus = res.alipayShopStatus
  }).catch(err =>{
    console.log(err)
  })
}

defineExpose({show})
</script>
